<template>
  <section>
    <el-form ref="myForm" :model="formData" label-width="100px">
      <el-row>
        <el-col :sm="12" :md="8" :lg="6">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :md="8" :lg="6">
          <el-form-item label="用户昵称" prop="nick_name">
            <el-input v-model="formData.nick_name" maxlength="16" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :md="8" :lg="6">
          <el-form-item label="真实姓名" prop="real_name">
            <el-input v-model="formData.real_name" maxlength="16" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :md="8" :lg="6">
          <el-form-item label="创建时间范围" prop="creator_time_range">
            <el-date-picker
              v-model="formData.creator_time_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-button
          type="primary"
          @click.prevent="handleQuery(1)"
          native-type="submit"
          >查询</el-button
        >
        <el-button @click="handleReset(myForm)">重置</el-button>
        <!-- 使用store的getters判断是否有权限，8表示用户管理的权限ID -->
        <el-button
          type="primary"
          @click="handleShow('insert')"
          v-if="store.getters.hasPermission(8)"
          >增加</el-button
        >
      </el-row>
    </el-form>
    <el-table :data="tableData" border>
      <el-table-column prop="mobile" label="手机号码"> </el-table-column>
      <el-table-column prop="nick_name" label="用户昵称"> </el-table-column>
      <el-table-column label="头像">
        <template #default="scope">
          <img :src="scope.row.avatar" class="image" />
        </template>
      </el-table-column>
      <el-table-column prop="real_name" label="真实姓名"> </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          <span>{{ getStatus(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="creator_time" label="创建时间">
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <div class="btn-box">
            <!-- 使用store的getters判断是否有权限，8表示用户管理的权限ID -->
            <el-button
              v-if="store.getters.hasPermission(8)"
              type="warning"
              :icon="Edit"
              circle
              plain
              text
              @click="handleShow('update', scope.row)"
            />
            <el-button
              v-if="store.getters.hasPermission(8)"
              type="danger"
              :icon="Delete"
              circle
              plain
              text
              @click="handleDelete(scope.row.id)"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :currentPage="formData.currentPage"
      :page-size="formData.pageSize"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </section>
</template>
<script lang="ts" setup>
import request from "@/utils/request";
import {
  computed,
  ref,
  reactive,
  defineEmits,
  defineProps,
  defineExpose,
} from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { FormInstance, ElMessageBox } from "element-plus";

// 引入页面需要用到的图标
import { Delete, Edit } from "@element-plus/icons-vue";

// 定义子传父的事件触发器
const emits = defineEmits(["show"]);

// 使用Vuex状态管理
const store = useStore();

// 表单参数
const formData = reactive<any>({});

// 表格数据
const tableData = reactive<Array<object>>([]);

// 总行数
const total = ref(0);


// 使用computed的setter和getter与查询参数的creator_time_begin和creator_time_end挂钩
formData.creator_time = computed({
  set(val: any) {
    formData.creator_time_begin = val ? val[0] : "";
    formData.creator_time_end = val ? val[1] : "";
  },
  get: () => [formData.creator_time_begin, formData.creator_time_end],
});

/**
 * 调用axios，查询数据
 */
const handleQuery = (currentPage: number) => {
  formData.currentPage = currentPage;
  formData.pageSize = formData.pageSize || 10;
  request({
    url: "/user/queryList",
    method: "POST",
    data: formData,
  }).then(({ data }) => {
    // 查询成功，将结果数据赋值到tableData中
    if (data.code > 0) {
      // 重置表格数据
      tableData.length = 0;
      // 将接口返回的数据数组，添加到表格数据中，tableData是响应式数据，表格组件会自动更新表格数据
      tableData.push(...data.data.list);
      // 将接口返回的总行数，赋值到total中，total传递到分页器组件中，会自动更新分页器组件中的数据
      total.value = data.data.total;
    }
  });
};

// 获取表单元素
const myForm = ref<FormInstance>();

/**
 * 当前页变化
 * @param currentPage 当前页
 */
const handleCurrentChange = (currentPage: number) => {
  handleQuery(currentPage);
};

/**
 * 每页行数变化
 * @param pageSize 每页行数
 */
const handleSizeChange = (pageSize: number) => {
  formData.pageSize = pageSize;
  handleQuery(1);
};

/**
 * 点击重置按钮：
 * 清空表单，完成数据查询
 */
const handleReset = (myForm: FormInstance | undefined) => {
  if (myForm) {
    myForm.resetFields();
  }
  handleQuery(1);
};

/**
 * 点击增加或修改按钮，显示增加或修改页面
 */
const handleShow = (value: "insert" | "update", rowData?: any) => {
  // 触发显示事件（子传父）
  emits("show", value, rowData);
};

/**
 * 获取状态
 * 1=审核中 2=草稿 7=被否决 8=禁用 9=已删除
 * @param status 状态
 */
const getStatus = (status: string) => {
  switch (status) {
    case "0":
      return "正常";
    case "1":
      return "审核中";
    case "2":
      return "草稿";
    case "7":
      return "被否决";
    case "8":
      return "禁用";
    case "9":
      return "已删除";
    default:
      return "未知";
  }
};

const handleDelete = (id: number) => {
  ElMessageBox.confirm("确认删除该选项吗，删除后用户将无法登录。", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    request({ url: `/user/delete/${id}`, method: "DELETE" }).then(
      ({ data }) => {
        if (data.code > 0) {
          alert("删除成功");
          handleReset(myForm.value);
        } else {
          alert("删除失败");
        }
      }
    );
  });
};

// 路由跳转对象
const router = useRouter();


handleReset(undefined);

// 将重置方法暴露给父组件
defineExpose({ handleReset });
</script>
<style lang="scss" scoped>
.el-table {
  margin-top: 15px;
  height: calc(100vh - 275px);
  width: 100%;

  .image {
    height: 100px;
    width: auto;
  }

  .btn-box {
    display: flex;
    justify-content: space-between;
  }
}
</style>